<?php
require_once 'bootstrap.php';

# define project's root url
if (!defined('ROOT_URL')) {
    preg_match('/(.*)\/public\/index\.php$/', $_SERVER['SCRIPT_NAME'], $m);
    $m = $m[1] . '/';
    define('ROOT_URL', $m);
}


# default controller
$request = 'canbo';

if (isset($_GET['request'])) {
    $request = $_GET['request'];
}

switch ($request) {
    case "login": $request = "canbo/login"; break;
    case "logout": $request = "canbo/logout"; break;
}
/**
 * Cắt request ra từng phần
 * canbo/view/123
 *  =>
 *      canbo   <- controller
 *      view    <- action
 *      123     <- argument
 */

# Đảm bảo $request tận cùng là 1 kí tự /
$request = rtrim($request, '/') . '/';
#get Controller
$controller = '';
if (preg_match('/^(.*?)\//', $request, $match)) {
    $controller = $match[1] . 'Controller';
    $request = str_replace($match[0], null, $request);
}

#get Action
$action = 'view';
if (preg_match('/^(.*?)\//', $request, $match)) {
    $action = $match[1];
    $request = str_replace($match[0], null, $request);
}

if (class_exists($controller)) {
    $dispatch = new $controller($action);
    if (method_exists($dispatch, $action)) {
        $dispatch->$action($request);
    }
} else {
    throw new Exception("Controller <strong>{$controller}</strong> không tồn tại!");
}
